package com.deyang.mycommon.util;

import android.app.Activity;

import com.deyang.mycommon.application.MyApplication;
import com.deyang.mycommon.config.HttpConfig;
import com.deyang.mycommon.entity.TokenInfo;
import com.deyang.mycommon.service.IHttpService;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;

/**
 * @author 王德阳
 * @data 创建时间: 2018/5/4 0004
 * @Description retrofit 请求
 */
public class RetrofitUtil {

    private static final String TAG = "RetrofitUtil";

    private static final long connectTime = 5000L;
    private static final long readTime = 5000L;

    private final OkHttpClient.Builder okHttpBuilder;
    private final OkHttpClient httpClient;

    private final Retrofit.Builder builder;

    private Retrofit retrofit;

    private MyApplication mApp;

    public RetrofitUtil(Activity activity) {
        mApp = (MyApplication) activity.getApplication();

        //日志打印
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                Logger.i(TAG, "retrofitBack = " + message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpBuilder = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .connectTimeout(connectTime, TimeUnit.MILLISECONDS)
                .readTimeout(readTime, TimeUnit.MILLISECONDS);

        final TokenInfo tokenInfo = mApp.getTokenInfo();
        if (tokenInfo != null) {
            okHttpBuilder.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                    Request original = chain.request();
                    Request request = original.newBuilder()
                            .header(HttpConfig.HEADER_AUTH, "Bearer " + tokenInfo.getAccess_token())
//                        .header("Accept", "application/vnd.yourapi.v1.full+json")
                            .method(original.method(), original.body())
                            .build();

                    return chain.proceed(request);
                }
            });
        }

        //其他配置
        httpClient = okHttpBuilder.build();


        builder = new Retrofit.Builder()
                .baseUrl(HttpConfig.HTTP_URL)
                .client(httpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create());

        retrofit = builder.build();
    }

    /**
     * 回到主线程的被观察者
     *
     * @param activity
     * @return
     */
    public Scheduler getMainUiScheduler(final Activity activity) {
        Scheduler mainThread = AndroidSchedulers.mainThread();
        return mainThread;
    }

    /**
     * 获取请求 Service
     *
     * @return
     */
    public IHttpService getHttpService() {
        return retrofit.create(IHttpService.class);
    }
}
